<template>
  <div>
    购物车展示
    <el-table :data="cartData" height="570" style="width: 100%" :cell-style="centerCellStyle"
      :header-cell-style="centerHeaderCellStyle" @selection-change="handleSelectionChange" :row-key="getRowKey">
      <!-- 多选列 -->
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column prop="name" label="名称" width="180" />
      <el-table-column prop="image" label="图片" width="180">
        <template #default="{ row }">
          <img :src="row.image" alt="" width="180px" height="180px" />
        </template>
      </el-table-column>
      <el-table-column prop="price" label="价格" />
      <el-table-column prop="description" label="描述" />
      <el-table-column prop="buyNum" label="购买数量" />
      <el-table-column label="总价">
        <template #default="{ row }">
          {{ row.price * row.buyNum }}
        </template>
      </el-table-column>
      <el-table-column label="订单状态">
        <template #default="{ row }">
          <span :style="{ color: row.status === 'yes' ? 'green' : 'red' }">
            {{ row.status === 'yes' ? '已支付' : '未支付' }}
          </span>
        </template>
      </el-table-column>
    </el-table>
    <!-- 显示选中项数量 -->
    <p>已选中 {{ selectedRows.length }} 项</p>
    <!-- 示例按钮，可根据需求添加更多操作 -->
    <el-button @click="handleDeleteSelected">删除选中项</el-button>
    <el-button @click="handleSettle">
      结算选中项（{{ settlementAmount }} 元）
    </el-button>
  </div>
</template>

<script setup>
import axios from "axios";
import { ref, onMounted, watch, inject } from "vue";

// 接收传递过来的背景颜色
const bgColor = inject('bgColor');
console.log(bgColor.value);


const cartData = ref([]);
const selectedRows = ref([]);
const settlementAmount = ref(0);

onMounted(async () => {
  try {
    const res = await axios("/api/goods/cart/getOrders");
    console.log(res);
    cartData.value = res.data.orders;
    console.log(cartData.value);
  } catch (error) {
    console.error("获取购物车数据失败:", error);
  }
});

// 表格内容居中
const centerCellStyle = () => {
  return { "text-align": "center", 'background-color': bgColor.value };
};

// 表格表头居中
const centerHeaderCellStyle = () => {
  return { "text-align": "center", 'background-color': bgColor.value };
};

// 处理选中项变化
const handleSelectionChange = (val) => {
  selectedRows.value = val;
};

// 计算结算金额
const calculateSettlementAmount = () => {
  const unpaidSelectedRows = selectedRows.value.filter(
    (row) => row.status === "no"
  );
  let total = 0;
  unpaidSelectedRows.forEach((row) => {
    total += row.price * row.buyNum;
  });
  settlementAmount.value = total;
};

// 监听选中项变化，实时计算结算金额
watch(selectedRows, () => {
  calculateSettlementAmount();
});

// 删除选中项
const handleDeleteSelected = async () => {
  if (selectedRows.value.length === 0) {
    alert("请选择要删除的项");
    return;
  }
  try {
    const idsToDelete = selectedRows.value.map((row) => row.id);
    const res = await axios.post("/api/goods/cart/deleteSelected", {
      ids: idsToDelete,
    });
    // 从本地数据中移除选中项
    cartData.value = cartData.value.filter((row) => !idsToDelete.includes(row.id));
    selectedRows.value = [];
    alert(res.data.message);
  } catch (error) {
    console.error("删除失败:", error);
    alert("删除失败");
  }
};

// 结算选中项
const handleSettle = async () => {
  if (selectedRows.value.length === 0) {
    alert("请选择要结算的项");
    return;
  }
  const unpaidSelectedRows = selectedRows.value.filter(
    (row) => row.status === "no"
  );
  if (unpaidSelectedRows.length === 0) {
    alert("选中的商品均已支付，无需结算");
    return;
  }
  try {
    const idsToSettle = unpaidSelectedRows.map((row) => row.id);
    const res = await axios.post("/api/goods/cart/settleSelected", {
      ids: idsToSettle,
    });
    // 更新本地数据的订单状态为已支付
    cartData.value = cartData.value.map((row) => {
      if (idsToSettle.includes(row.id)) {
        return { ...row, status: "yes" };
      }
      return row;
    });
    selectedRows.value = [];
    alert(`结算成功，总金额为：${settlementAmount.value} 元`);
    settlementAmount.value = 0;
  } catch (error) {
    console.error("结算失败:", error);
    alert("结算失败");
  }
};

// 指定表格行的唯一 key
const getRowKey = (row) => {
  return row.id; // 假设数据中有唯一的 id 字段
};
</script>

<style scoped></style>